// src/common/multer-config.service.ts
import { Injectable } from '@nestjs/common';
import { diskStorage } from 'multer';
import { v4 as uuidv4 } from 'uuid';
import * as path from 'path';
import * as fs from 'fs';
import * as process from "node:process";
@Injectable()
export class MulterConfigService {
  private readonly basePath = path.resolve(process.cwd(),'public/images');

  public getMulterOptions(): any {
    return {
      storage: diskStorage({
        destination: (req, file, callback) => {
          const folder = this.getFolderByMimeType(file.mimetype);
          const destinationPath = path.join(this.basePath, folder);
          fs.mkdirSync(destinationPath, { recursive: true }); // Ensure the directory exists
          callback(null, destinationPath);
        },
        filename: (req, file, callback) => {
          const fileExtName = path.extname(file.originalname);
          const fileName = uuidv4() + fileExtName; // Ensure unique file names
          callback(null, fileName);
        },
      }),
    };
  }

  private getFolderByMimeType(mimeType: string): string {
    const type = mimeType.split('/')[0]; // 'image', 'video', etc.
    switch (type) {
      case 'image':
        return 'images';
      case 'video':
        return 'videos';
      case 'audio':
        return 'audio';
      default:
        return 'files'; // Default folder for other types
    }
  }
}
